package com.lelefly.base.daoimp;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;

import com.lelefly.base.daoimp.BaseDao;
import com.lelefly.base.po.LeleflyOrganization;
import com.lelefly.base.po.LeleflyUser;
import com.lelefly.constant.Constant;
import com.lelefly.db.dbmanager.HibernateSessionFactory;

@Repository
public class LeleflyuserDao extends BaseDao{

	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	public LeleflyUser getLeleflyUserReUnique(String hql){
		
		SessionFactory sessionFactory = HibernateSessionFactory
				.getSessionFactory();
		Session session = sessionFactory.openSession();
		try {
			Query query = session.createQuery(hql);
			return (LeleflyUser) query.uniqueResult();
		} catch (Exception e) {
			// TODO: handle exception
			getLogger().info("----->>>" + e.getMessage());
			throw e;
		} finally {
			session.close();
		}
		
	}
	
	/**
	 * 保存组织注册账户信息
	 * @param user
	 * @return
	 */
	public int saveOrganizationUser(LeleflyUser user){
		int state = Constant.DB_STATUS_FAIL;
		SessionFactory sessionFactory = HibernateSessionFactory
				.getSessionFactory();
		Session session = sessionFactory.openSession();
		
		Transaction transaction = null;
		try {
			LeleflyOrganization organization = new LeleflyOrganization();
			organization.setOrganizationId(user.getPhonenumber() + System.currentTimeMillis());
			organization.setOrganizationCreator(user.getPhonenumber());
			organization.setOrganizationName(user.getOrganization());
			organization.setOrganizationOwner(user.getPhonenumber());
			organization.setRegisterDate(sdf.format(new Date()));
			transaction = session.beginTransaction();
			session.save(user);
			session.save(organization);
			
			transaction.commit();
			state = Constant.DB_STATUS_SUCCESS;
		} catch (Exception e) {
			getLogger().info("注册出错：" + e.getMessage());
			transaction.rollback();
		}finally {
			session.close();
		}
		
		return state;
	}
}
